<template>
  <el-drawer size="40%" v-model="drawer" :title="formData.roleId != 0 ? '修改角色' : '添加角色'" direction="rtl"
    :before-close="closeDrawer">
    <el-form size="small" ref="formRef" style="max-width: 600px" :model="formData" status-icon :rules="rules"
      label-width="60px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model.number="formData.roleName" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(formRef)">
          {{ formData.roleId != 0 ? '修改' : '添加' }}
        </el-button>
        <el-button @click="resetForm">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElNotification } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { $add, $update } from "../../api/role";

// 同步列表
const emits = defineEmits(['sync-list', 'update'])

// 抽屉变量
const drawer = ref(false)
// 关闭抽屉
const closeDrawer = () => {
  drawer.value = false
  // 重置表单
  formRef.value?.resetFields()
  formData.value = {
    roleName: '',
    roleId: 0
  }
}
// 定义一个ref对象绑定表单
const formRef = ref<FormInstance>()

// 表单数据
const formData = ref({
  roleName: '',
  roleId: 0
})
// 验证角色名称
const validateRoleName = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入角色名称'))
  } else {
    callback()
  }
}

// 验证对象
const rules = reactive<FormRules<typeof formData>>({
  roleName: [{ validator: validateRoleName, trigger: 'blur' }],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      let ret
      if (formData.value.roleId) {
        ret = await $update(formData.value)
      } else {
        ret = await $add(formData.value)
      }
      if (ret.success) {
        ElNotification({
          title: '提示',
          message: ret.message,
          type: 'success',
        })
        // 通知父组件更新列表
        emits('sync-list')
        emits('update', formData)
        // 重置表单
        formRef.value?.resetFields()

      } else {
        ElNotification({
          title: '提示',
          message: ret.message,
          type: 'error',
        })
      }
      drawer.value = false
    } else {
      console.log("提交失败");
    }
  })
}

const resetForm = () => {
  drawer.value = false
}

// 暴露成员
defineExpose({
  drawer,
  formData
})

</script>

<style lang="scss" scoped></style>